import { $msg } from '@/core/msg'
import { setCache, getCache } from '@/core/storage'
import { $get, $postB } from '@/core/request'
import { subscribeMsg } from '@/core/wx.js'
import { SESSION_KEY, PHONE_NO, OPEN_ID, UNION_ID, TOKEN, } from '@/config/constant'
import { RESOURCE_TYPE } from '@/config/enum.js'

export function login2WX() {
	return new Promise(async (resolve, reject) => {
		uni.login({
			success: async ({ code: jsCode }) => {
				let { success, data: { data } } = await $get('/wechat/mini/login', { jsCode },
					false);
				if (success) {
					let { openid, session_key, unionid } = data
					setCache(SESSION_KEY, session_key)
					setCache(OPEN_ID, openid)
					setCache(UNION_ID, unionid)
					resolve()
				} else reject()
			},
			fail(e) {
				console.log(e);
				reject(e)
			}
		})
	})
}


/**
 * 获取微信支付的预下单ID
 */
export async function buySth(payItems) {
	try {
		//订阅支付消息
		await subscribeMsg()

		let { data } = await $postB('/pay/pre/order/mini', {
			payItems,
			openid: getCache(OPEN_ID),
			unionId: getCache(UNION_ID)
		})
		if (!data) return false
		if (data.returnCode === 'PARAM_ERROR')
			return console.log('下单报错', data.returnMsg);

		await $pay(data.result)

		return true
	} catch (e) {
		console.log('errMsg', e);
		return false
	}
}


/**
 * 支付方法
 * @param {Object} nonceStr
 * @param {Object} prepay_id
 * @param {Object} paySign
 * @param {Object} timeStamp
 */
function $pay(payArgs) {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			nonceStr: payArgs.nonce_str,
			package: 'prepay_id=' + payArgs.prepay_id,
			paySign: payArgs.sign,
			signType: "RSA",
			timeStamp: payArgs.timestamp,
			success: res => resolve(res),
			fail: (err) => {
				console.log('errMsg', err);
				reject()
			}
		})
	})
}
